<?php
/**
 * 管理元后台
 * User: huyi
 * Date: 2018/9/29
 * Time: 9:53
 */
namespace app\Admin\controller;

use app\api\controller\Upload;
use app\common\controller\AdminBase;
use app\common\controller\CommonShare;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Session;
use think\Request;

class Admin extends AdminBase{
    private $ude = array();

    public function index(){
        $teachers = Db::name('users')->where(array('usertype' => 2))->order('id', 'desc')->paginate(10);
        $page     = $teachers->render();
        $url      = 'http://' . $_SERVER['HTTP_HOST'] . '/template.xlsx';
        $this->assign('url', $url);
        $this->assign('page', $page);
        return $this->fetch('index', array('admin_user_list' => $teachers));
    }

    public function add(){
        return $this->fetch('add');
    }

    public function save(Request $request){
        $data = $request->post();
        if(strlen($data['userLoginName']) > 20){
            return json(array('code' => 0, 'msg' => '用户名限制20个字符(1中文等于3字符)'));
        }
        if(strlen($data['name']) > 20){
            return json(array('code' => 0, 'msg' => '昵称限制20个字符(1中文等于3字符)'));
        }
        if(strlen($data['mobile']) > 20){
            return json(array('code' => 0, 'msg' => '联系方式长度超过20字符'));
        }

        if($data['userPassword'] != $data['confirm_password']){
            return json(array('code' => 0, 'msg' => '密码不一致！'));
        }
        if(strlen($data['userPassword']) < 6 || strlen($data['userPassword']) > 15){
            return json(array('code' => 0, 'msg' => '密码长度必须在6-15位之间！'));
        }
        if(trim($data['userPassword']) == '' || trim($data['userLoginName']) == '' || trim($data['name']) == '' || trim($data['male'] == '')){
            return json(array('code' => 0, 'msg' => '*是必填项！'));
        }
        //不允许特殊字符
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['name'])){
            $this->error('昵称不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['userLoginName'])){
            $this->error('用户名不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['userPassword'])){
            $this->error('密码不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['address'])){
            $this->error('地址不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['company'])){
            $this->error('公司名不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['country'])){
            $this->error('国家名不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['description'])){
            $this->error('描述不能包含特殊字符！');
        }
        if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $data['mobile'])){
            $this->error('电话号码不能包含特殊字符！');
        }
        if(isset($data['mobile']) && !empty($data['mobile']) && !is_numeric($data['mobile'])){
            $this->error('电话号码只能是数字！');
        }

        //入库 本地库bhmd5
        unset($data['confirm_password']);
        $data['usertype']     = 2; //表示教师
        $register             = new CommonShare();
        $result               = $register->register($data);
        $data['userPassword'] = bhmd5(trim($data['userPassword']));
        if($result === true){
            $r = 0;
            try{
                $r = Db::name('users')->insertGetId($data);
            }
            catch(Exception $e){
                Db::name('users')->where('userLoginName', $data['userLoginName'])->update($data);
                $this->success('添加成功~~');
            }
            if($r > 0){
                //take data to origin system  interface
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        $this->error('添加失败');
    }

    public function delete(){
        $id  = input('id');
        $res = Db::name('users')->where('id', $id)->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function backInfo(){
        $config = Config::get('AdminUser');
        return json($config);
    }

    public function upload(){
        ini_set('memory_limit', '128M');
        ini_set("max_execution_time", "1800");
        //上传
        if(!empty($_FILES)){
            $files  = request()->file('teachers');
            $extion = pathinfo($_FILES['teachers']['name'], PATHINFO_EXTENSION);
            if(empty($files)){
                $this->error("请选择要导入的excel文件!");
            }

            if($extion == 'xlsx' || $extion == 'xls'){
                $upload_path = str_replace('\\', '/', ROOT_PATH . '/public/uploads');
                $info        = $files->move($upload_path);
                if($info){
                    $excel     = new \PHPExcel();
                    $file_name = $upload_path . '/' . $info->getSaveName();
                    $ext       = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    if($ext == 'xlsx'){
                        $boj      = \PHPExcel_IOFactory::createReader('Excel2007');
                        $objexcel = $boj->load($file_name, $encode = 'utf-8');
                    }elseif($ext == 'xls'){
                        $boj      = \PHPExcel_IOFactory::createReader('Excel5');
                        $objexcel = $boj->load($file_name, $encode = 'utf-8');
                    }

                    $sheet = $objexcel->getSheet(0);
                    //行数
                    $hight = $sheet->getHighestRow();
                    //列数
                    $column    = $sheet->getHighestColumn();
                    $dataExcel = array();
                    for($rowIndex = 1; $rowIndex <= $hight; $rowIndex++){
                        for($colIndex = "A"; $colIndex <= $column; $colIndex++){
                            $location = $colIndex . $rowIndex;

                            $cell = $sheet->getCell($location)->getValue();

                            if($cell instanceof \PHPExcel_RichText){ // 富文本转换字符串
                                $cell = $cell->__toString();
                            }
                            //过滤100行之后的空行数据
                            if(!empty($cell)){
                                $dataExcel[$rowIndex][$colIndex] = $cell;
                            }
                        }
                    }

                    $r              = ["status" => 1, "info" => "文件内容获取成功"];
                    $r["data"]      = $dataExcel;
                    $r["allRow"]    = $hight;
                    $r["allColumn"] = $column;
                    if($r['status'] == 1){
                        if(isset($r['data'][2])){
                            array_shift($r['data']);
                            $res = $this->upOnline($r['data']);
                            if($res == 1){
                                if(count($r['data']) > 70){
                                    cookie('results', '导入成功！', 22);//5秒cookie
                                }elseif(count($r['data']) <= 70 && count($r['data']) >= 40){
                                    cookie('results', '导入成功！', 15);//5秒cookie
                                }else{
                                    cookie('results', '导入成功！', 5);//5秒cookie
                                }
                                $this->redirect("admin/admin/index");
                                exit(0);
                            }else{
                                $this->error("导入失败");
                            }
                        }else{
                            $this->error("导入失败,请填写数据");
                        }
                    }else{
                        $this->error("导入失败");
                    }
                }
            }else{
                $this->error("请导入excel文件!");
            }
        }else{
            $this->error("请选择要导入的excel文件");
        }
    }

    public function upOnline($data){
        if(count($data) > 100){
            exit("<script>alert('导入记录数量限制100条以内!');window.location.href='/index.php/admin/admin/index';</script>");
            //$this->redirect("admin/admin/index");
        }
        $re = true;
        try{
            $re = $this->checkExcel($data);
        }
        catch(Exception $e){
            cookie('errorss', 'excel文件不合法', 3);
            $this->redirect("admin/admin/index");
        }

        foreach($this->ude as $kk){
            unset($data[$kk]);
        }

        if($re !== true){
            switch($re){
                case false:
                    cookie('errorss', '导入失败,请把必填数据填写！', 3);
                    break;
                case 'a':
                    cookie('errorss', '用户名限制20个字符(1中文等于3字符)', 3);
                    break;
                case 'b':
                    cookie('errorss', '昵称限制20个字符(1中文等于3字符)', 3);
                    break;
                case 'c':
                    cookie('errorss', '联系方式长度超过20字符', 3);
                    break;
                case 'd':
                    cookie('errorss', '昵称不能包含特殊字符', 3);
                    break;
                case 'e':
                    cookie('errorss', '用户名不能包含特殊字符', 3);
                    break;
                case 'f':
                    cookie('errorss', '密码不能包含特殊字符！', 3);
                    break;
                case 'g':
                    cookie('errorss', '地址不能包含特殊字符！', 3);
                    break;
                case 'h':
                    cookie('errorss', '公司名不能包含特殊字符！', 3);
                    break;
                case 'i':
                    cookie('errorss', '描述不能包含特殊字符', 3);
                    break;
                case 'j':
                    cookie('errorss', '描述不能包含特殊字符', 3);
                    break;
                case 'k':
                    cookie('errorss', '电话号码不能包含特殊字符', 3);
                    break;
                case 'zz':
                    cookie('errorss', '电话号码只能是数字！', 3);
                    break;
            }
            $this->redirect("admin/admin/index");
            exit(0);
        }

        $arr   = array();
        $array = array();
        $r     = true;
        foreach($data as $k => $v){
            $arr['userLoginName'] = $v['A'];
            $arr['userPassword']  = $v['B'];
            $arr['name']          = $v['C'];
            $arr['male']          = $v['D'];
            $arr['mobile']        = !isset($v['E']) ? '' : trim($v['E']);
            $arr['address']       = !isset($v['F']) ? '' : trim($v['F']);
            $arr['company']       = !isset($v['G']) ? '' : trim($v['G']);
            $arr['country']       = !isset($v['H']) ? '' : trim($v['H']);
            $arr['description']   = !isset($v['I']) ? '' : trim($v['I']);
            $register             = new CommonShare();
            $r                    = $register->register($arr, 'batch');
            $arr['male']          = $v['D'] == '男' ? 'true' : 'false';
            $arr['userPassword']  = bhmd5($v['B']);
            $arr['usertype']      = 2;
            $array[]              = $arr;

            $rr = Db::name('users')->where('userLoginName', $arr['userLoginName'])->find();
            if($rr){
                Db::name('users')->where('userLoginName', $arr['userLoginName'])->update($arr);
            }else{
                Db::name('users')->insert($arr);
            }
        }
        return 1;
    }

    public function checkExcel($data){
        $check = true;
        foreach($data as $k => $v){
            if(empty(trim($v['A'])) && empty(trim($v['B'])) && empty(trim($v['C'])) && empty(trim($v['D']))){
                $this->ude[] = $k;
                continue;
            }
            if(empty(trim($v['A'])) || empty(trim($v['B'])) || empty(trim($v['C'])) || empty(trim($v['D']))){
                $check = false;
                return $check;
            }

            $userLoginName = $v['A'];
            $userPassword  = $v['B'];
            $name          = $v['C'];
            $male          = $v['D'];
            $mobile        = !isset($v['E']) ? '' : trim($v['E']);
            $address       = !isset($v['F']) ? '' : trim($v['F']);
            $company       = !isset($v['G']) ? '' : trim($v['G']);
            $country       = !isset($v['H']) ? '' : trim($v['H']);
            $description   = !isset($v['I']) ? '' : trim($v['I']);

            if(strlen($userLoginName) > 20){
                $check = 'a';
                return $check;
            }
            if(strlen($name) > 20){
                $check = 'b';
                return $check;
            }
            if(strlen($mobile) > 20){
                $check = 'c';
                return $check;
            }
            //不允许特殊字符
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $name)){
                $check = 'd';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $userLoginName)){
                $check = 'e';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $userPassword)){
                $check = 'f';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $address)){
                $check = 'g';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $company)){
                $check = 'h';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $country)){
                $check = 'i';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $description)){
                $check = 'j';
                return $check;
            }
            if(preg_match("/[\'.,:;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $mobile)){
                $check = 'k';
                return $check;
            }
            if(isset($mobile) && !empty($mobile) && !is_numeric($mobile)){
                $check = 'zz';
                return $check;
            }
        }
        return $check;
    }

    public function get_microtime(){
        list($usec, $sec) = explode(' ', microtime());
        return (float) $usec + (float) $sec;
    }

}